package yxy.game.pm2.command;

import com.alibaba.fastjson.JSONArray;
import yxy.apple.util.concurrent.ThreadPoolManager;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActOpenHandle;
import yxy.game.pm2.active.module.ActiveModule;
import yxy.game.pm2.active.module.ActiveModule_七日登陆;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.MainMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.conquest.ConquestHandle;
import yxy.game.pm2.module.conquest.ConquestModule;
import yxy.game.pm2.module.dungeon.DungeonHandle;
import yxy.game.pm2.module.fortdefeat.FortDefeatHandle;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.player.FunctionHandle;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.player.PlayerInitHandle;
import yxy.game.pm2.module.player.WorldLevelHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tower.TowerHandle;

import java.util.Date;


/**
 * 综合 玩家开始游戏
 */
@MessageType(proto = Command.StartGame, classtype = MainMessage.StartGameRequest.class)
public class CMD_StartGame extends Command<MainMessage.StartGameRequest> {

    @Override
    public void execute(MessageSource messageSource, MainMessage.StartGameRequest request) {
        Date date = new Date();
        String playerCode = messageSource.getTag();

        MainMessage.StartGameResponse.Builder response = MainMessage.StartGameResponse.newBuilder();

        //根据数据库有没有用户角色信息，没有的就是新用户，直接跳过各种查数据库操作
        Boolean isNewPlayer = false;
        PlayerBean playerBean = null;
        try {
            playerBean = MySQLCacheDAO.getV(String.format("PLAYER:%s:INFO", playerCode), PlayerBean.class);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
        if (playerBean == null) isNewPlayer = true;
        
        PlayerBean player = PlayerBean.get(playerCode);
        PlayerInitHandle playerInitHandle = new PlayerInitHandle();

        Runnable run = () -> {
            //初始化
            try {
                playerInitHandle.initPlayer(player);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        ThreadPoolManager.getInstance().execute(run);

        HeroHandle.calculationPower(playerCode);


        // 玩家信息 名字 等级 经验 头像

        response.setPlayerinfo(new PlayerHandle().playerInfo(player));

        response.setWorldlevel(WorldLevelHandle.getLevel(player));


        //返回开服时间
        Long serverStartTime = new FunctionHandle().getServerStartTime(player);
        response.setServerStartTime(Integer.parseInt(String.valueOf(serverStartTime)));


        // 代币信息
        response.addAllCurrency(new CurrencyHandle().allPoint(playerCode, isNewPlayer));

        {
            //七日登录因为涉及到新手教程，所以不放异步
            {
                try {
                    ActiveModule_七日登陆.get(playerCode, isNewPlayer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            Boolean finalIsNewPlayer = isNewPlayer;
            Runnable runnable = () -> {
                try {
                    // 活动信息
                    ActiveModule.initAct(playerCode, finalIsNewPlayer);
                    //红点信息
                    TipHandle tipHandle = new TipHandle();
                    tipHandle.update(playerCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
            ThreadPoolManager.getInstance().execute(runnable);
        }

        // 设置
        // 征战
        {
            ConquestModule conquestModule = ConquestModule.get(playerCode);
            int mapId = conquestModule.getMapId();
            long time = new ConquestHandle().get挂机时长(conquestModule);

            response.setMapId(mapId);
            response.setTime(time);
        }

        // 战斗信息
        // 征战
        {
            BattleMessage.BattlePlayBack playback = new ConquestHandle().getBattling(playerCode);
            if (playback != null) {
                response.addBattles(playback);
            }
        }

        // 爬塔
        {
            BattleMessage.BattlePlayBack playback = new TowerHandle().getBattling(playerCode);
            if (playback != null) {
                response.addBattles(playback);
            }
        }

        // 日常副本
        {
            BattleMessage.BattlePlayBack playback = new DungeonHandle().getBattling(playerCode);
            if (playback != null) {
                response.addBattles(playback);
            }
        }

        // 过关斩将
        {
            BattleMessage.BattlePlayBack playback = new FortDefeatHandle().getBattling(playerCode);
            if (playback != null) {
                response.addBattles(playback);
            }
        }

        // 新手引导
        {
            String guide = player.getGuide();
            response.setGuide(guide == null ? "" : guide);
        }

        // 未完成订单号
        {
            System.out.println("查询所有订单号");
            JSONArray arr = OrderInfoModule.getRunningOrderInfoId(playerCode);
            response.setOrderids(arr.toString());
        }

        {
            ActOpenHandle actopenHandle = new ActOpenHandle();
            response.addAllActopens(actopenHandle.all(playerCode));
        }

        send(messageSource, response, Result.Success);

        Date date1 = new Date();
        System.out.println("CMD_StartGame:" + (date1.getTime() - date.getTime()));
    }

    private void send(MessageSource messageSource, MainMessage.StartGameResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }


}